package com.xiaobai.itextpdf;

import com.itextpdf.text.BadElementException;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfGState;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import org.junit.jupiter.api.Test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author wangtw
 * @ClassName PdfUtil
 * @description: pdf工具类
 * @date 2024/1/1621:17
 */
public class PdfUtil {

    @Test
    public void addImage() {
        String pdfPath = "/Users/outenmon/Public/工作资料/公告/aaaa.pdf";
        PdfReader reader = null;
        try {
            reader = new PdfReader(pdfPath, "PDF".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
        String outPdfFile = "/Users/outenmon/Public/工作资料/公告/bbbb.pdf";
        PdfStamper stamp = null;
        try {
            stamp = new PdfStamper(reader, new FileOutputStream(new File(outPdfFile)));
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        PdfContentByte under;

//        PdfGState gs1 = new PdfGState();
//        gs1.setFillOpacity(0.3f);// 透明度设置

        String imagePath = ImageUtil.createImage();
        Image img = null;// 插入图片水印
        try {
            img = Image.getInstance(imagePath);
        } catch (BadElementException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        Rectangle pageSize1 = reader.getPageSize(1);
        float height = pageSize1.getHeight();
        img.setAbsolutePosition(10, height - 50); // 坐标
        // img.setRotation(-20);// 旋转 弧度
        // img.setRotationDegrees(45);// 旋转 角度
//        img.scaleAbsolute(80, 30);// 自定义大小
        // img.scalePercent(50);//依照比例缩放

//        int pageSize = reader.getNumberOfPages();// 原pdf文件的总页数
        /*for (int i = 1; i <= pageSize; i++) {
            under = stamp.getUnderContent(i);// 水印在之前文本下
            // under = stamp.getOverContent(i);//水印在之前文本上
            under.setGState(gs1);// 图片水印 透明度
            try {
                under.addImage(img);// 图片水印
            } catch (DocumentException e) {
                e.printStackTrace();
            }
        }*/
        under = stamp.getUnderContent(1);// 水印在之前文本下
        // under = stamp.getOverContent(i);//水印在之前文本上
//        under.setGState(gs1);// 图片水印 透明度
        try {
            under.addImage(img);// 图片水印
        } catch (DocumentException e) {
            e.printStackTrace();
        }

        try {
            stamp.close();// 关闭
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
